// 录制状态管理
import { defineStore } from 'pinia'
import { recordingService } from '../services/recordingService.js'

export const useRecordingStore = defineStore('recording', {
  state: () => ({
    // 录制状态
    isRecording: false,
    isPaused: false,
    recordingSteps: [], // 录制的步骤
    currentSession: null, // 当前录制会话
    
    // 录制统计信息
    recordingStats: {
      startTime: null,
      endTime: null,
      totalActions: 0,
      totalPageNavigations: 0,
      totalInputs: 0,
      totalClicks: 0
    }
  }),

  getters: {
    recordingDuration: (state) => {
      if (!state.recordingStats.startTime) return 0
      const endTime = state.recordingStats.endTime || new Date()
      return endTime - state.recordingStats.startTime
    },
    
    formattedDuration: (state) => {
      const duration = state.recordingDuration
      const seconds = Math.floor(duration / 1000) % 60
      const minutes = Math.floor(duration / (1000 * 60))
      return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    },
    
    hasRecordedSteps: (state) => state.recordingSteps.length > 0,
    
    recordingStatus: (state) => {
      if (state.isRecording && !state.isPaused) return 'recording'
      if (state.isRecording && state.isPaused) return 'paused'
      if (state.hasRecordedSteps && !state.isRecording) return 'completed'
      return 'ready'
    }
  },

  actions: {
    // 开始录制
    async startRecording(options = {}) {
      try {
        const { startUrl = 'https://www.baidu.com', name } = options
        
        // 如果已在录制中，先停止当前录制
        if (this.isRecording) {
          console.log('检测到正在录制，先停止当前录制...')
          await this.forceStopRecording()
        }
        
        // 重置所有状态
        this.reset()
        
        // 使用录制服务启动录制
        const result = await recordingService.startRecording(startUrl)
        
        if (!result.success) {
          throw new Error(result.error || '启动录制失败')
        }

        // 更新状态
        this.isRecording = true
        this.isPaused = false
        this.recordingSteps = []
        this.currentSession = {
          id: result.sessionId,
          startUrl: startUrl,
          name: name || `录制会话 ${new Date().toLocaleString()}`,
          mode: result.mode || 'simulation'
        }

        // 重置统计信息
        this.recordingStats = {
          startTime: new Date(),
          endTime: null,
          totalActions: 0,
          totalPageNavigations: 0,
          totalInputs: 0,
          totalClicks: 0
        }

        // 启动录制状态监听
        this.startRecordingStatusListener()

        console.log('开始录制:', this.currentSession)
        
        return { success: true, sessionId: this.currentSession.id, mode: result.mode }
      } catch (error) {
        console.error('启动录制失败:', error)
        // 确保在失败时重置状态
        this.isRecording = false
        this.currentSession = null
        return { success: false, error: error.message }
      }
    },

    // 停止录制
    async stopRecording() {
      if (!this.isRecording) {
        console.log('当前没有进行录制')
        return { success: false, error: '当前没有进行录制' }
      }

      try {
        console.log('停止录制...')

        // 使用录制服务停止录制
        const result = await recordingService.stopRecording()

        if (result.success) {
          // 更新状态
          this.isRecording = false
          this.isPaused = false
          this.recordingStats.endTime = new Date()
          
          // 更新录制步骤
          this.recordingSteps = result.steps || []
          
          console.log('录制已停止，共录制', this.recordingSteps.length, '个步骤')
          
          return {
            success: true,
            steps: this.recordingSteps,
            session: this.currentSession,
            stats: this.recordingStats,
            script: result.script, // 包含生成的脚本
            mode: result.mode || this.currentSession?.mode
          }
        } else {
          // 即使服务返回失败，也要重置本地状态
          this.isRecording = false
          this.isPaused = false
          return result
        }
      } catch (error) {
        console.error('停止录制失败:', error)
        // 发生错误时也要重置状态
        this.isRecording = false
        this.isPaused = false
        return { success: false, error: error.message }
      }
    },

    // 强制停止录制（用于重置状态）
    async forceStopRecording() {
      try {
        console.log('强制停止录制...')
        
        // 停止录制服务
        await recordingService.stopRecording()
        
        // 重置状态
        this.isRecording = false
        this.isPaused = false
        this.stopRecordingStatusListener()
        
        console.log('强制停止录制完成')
      } catch (error) {
        console.warn('强制停止录制时出错:', error)
        // 即使出错也要重置状态
        this.isRecording = false
        this.isPaused = false
        this.stopRecordingStatusListener()
      }
    },

    // 暂停录制
    pauseRecording() {
      if (!this.isRecording) return false
      
      this.isPaused = true
      console.log('录制已暂停')
      return true
    },

    // 恢复录制
    resumeRecording() {
      if (!this.isRecording || !this.isPaused) return false
      
      this.isPaused = false
      console.log('录制已恢复')
      return true
    },

    // 添加录制步骤
    addRecordedStep(stepData) {
      if (!this.isRecording || this.isPaused) return false

      const step = {
        id: this.generateStepId(),
        stepNumber: this.recordingSteps.length + 1,
        timestamp: new Date().toISOString(),
        sessionId: this.currentSession?.id,
        ...stepData
      }

      this.recordingSteps.push(step)
      this.updateStats(step)

      console.log('添加录制步骤:', step)
      return step
    },

    // 更新统计信息
    updateStats(step) {
      this.recordingStats.totalActions++
      
      switch (step.type) {
        case 'navigation':
          this.recordingStats.totalPageNavigations++
          break
        case 'input':
        case 'type':
          this.recordingStats.totalInputs++
          break
        case 'click':
          this.recordingStats.totalClicks++
          break
      }
    },

    // 删除步骤
    removeRecordedStep(stepIndex) {
      if (stepIndex >= 0 && stepIndex < this.recordingSteps.length) {
        this.recordingSteps.splice(stepIndex, 1)
        // 重新编号
        this.recordingSteps.forEach((step, index) => {
          step.stepNumber = index + 1
        })
        return true
      }
      return false
    },

    // 编辑步骤
    editRecordedStep(stepIndex, updates) {
      if (stepIndex >= 0 && stepIndex < this.recordingSteps.length) {
        this.recordingSteps[stepIndex] = {
          ...this.recordingSteps[stepIndex],
          ...updates,
          lastModified: new Date().toISOString()
        }
        return true
      }
      return false
    },

    // 清空录制步骤
    clearRecordedSteps() {
      this.recordingSteps = []
      this.recordingStats.totalActions = 0
      this.recordingStats.totalPageNavigations = 0
      this.recordingStats.totalInputs = 0
      this.recordingStats.totalClicks = 0
    },

    // 生成会话ID
    generateSessionId() {
      return `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    },

    // 生成步骤ID
    generateStepId() {
      return `step_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    },

    // 清理录制状态（调试用）
    cleanup() {
      console.log('清理录制状态...')
      this.forceStopRecording()
      this.reset()
      recordingService.forceCleanupRecording()
      return { success: true, message: '录制状态已清理' }
    },

    // 重置所有状态
    reset() {
      this.isRecording = false
      this.isPaused = false
      this.recordingSteps = []
      this.currentSession = null
      this.recordingStats = {
        startTime: null,
        endTime: null,
        totalActions: 0,
        totalPageNavigations: 0,
        totalInputs: 0,
        totalClicks: 0
      }
      
      // 停止录制状态监听
      this.stopRecordingStatusListener()
    },

    // 启动录制状态监听 - 实现实时步骤同步
    startRecordingStatusListener() {
      if (typeof window !== 'undefined') {
        // 监听录制状态更新事件
        this.recordingStatusUpdateHandler = (event) => {
          const { steps, stepCount } = event.detail
          if (steps && Array.isArray(steps)) {
            // 实时更新步骤列表
            this.recordingSteps = steps
            
            // 更新统计信息
            this.updateStatsFromSteps(steps)
          }
          console.log(`🔄 录制状态实时更新: ${stepCount || this.recordingSteps.length} 个步骤`)
        }
        
        // 监听单个步骤录制事件 - 实现逐步同步
        this.stepRecordedHandler = (event) => {
          const { step, totalSteps, sessionId } = event.detail
          
          // 验证会话ID匹配
          if (sessionId === this.currentSession?.id) {
            // 检查步骤是否已存在（避免重复）
            const existingStep = this.recordingSteps.find(s => 
              s.stepNumber === step.stepNumber || 
              (s.timestamp === step.timestamp && s.type === step.type)
            )
            
            if (!existingStep) {
              // 添加新步骤
              this.recordingSteps.push(step)
              this.updateStats(step)
              
              console.log(`新步骤录制: ${step.stepNumber}. ${step.name}`)
              
              // 触发Vue组件更新事件
              this.notifyStepAdded(step)
            }
          }
        }
        
        // 监听录制会话恢复事件
        this.recordingSessionRestoredHandler = (event) => {
          const { sessionId, recordingUrl } = event.detail
          console.log('恢复录制会话:', sessionId)
          
          // 恢复录制状态
          this.isRecording = true
          this.currentSession = {
            id: sessionId,
            startUrl: recordingUrl,
            name: `恢复的录制会话 ${new Date().toLocaleString()}`,
            mode: 'restored'
          }
        }
        
        // 监听录制清理事件
        this.recordingCleanedUpHandler = () => {
          console.log('录制状态已清理')
          this.reset()
        }
        
        // 注册所有事件监听器
        window.addEventListener('recordingStatusUpdated', this.recordingStatusUpdateHandler)
        window.addEventListener('stepRecorded', this.stepRecordedHandler)
        window.addEventListener('recordingSessionRestored', this.recordingSessionRestoredHandler)
        window.addEventListener('recordingCleanedUp', this.recordingCleanedUpHandler)
      }
    },

    // 从步骤列表更新统计信息
    updateStatsFromSteps(steps) {
      // 重置统计
      this.recordingStats.totalActions = steps.length
      this.recordingStats.totalPageNavigations = 0
      this.recordingStats.totalInputs = 0
      this.recordingStats.totalClicks = 0
      
      // 重新计算统计
      steps.forEach(step => {
        switch (step.type) {
          case 'navigation':
            this.recordingStats.totalPageNavigations++
            break
          case 'input':
          case 'type':
          case 'fill':
            this.recordingStats.totalInputs++
            break
          case 'click':
            this.recordingStats.totalClicks++
            break
        }
      })
    },

    // 通知步骤添加（用于UI响应）
    notifyStepAdded(step) {
      // 可以在这里添加UI通知逻辑
      // 例如：滚动到最新步骤、高亮显示等
      if (typeof window !== 'undefined') {
        const event = new CustomEvent('stepAddedToUI', {
          detail: { step, totalSteps: this.recordingSteps.length }
        })
        window.dispatchEvent(event)
      }
    },

    // 停止录制状态监听
    stopRecordingStatusListener() {
      if (typeof window !== 'undefined') {
        // 移除所有事件监听器
        if (this.recordingStatusUpdateHandler) {
          window.removeEventListener('recordingStatusUpdated', this.recordingStatusUpdateHandler)
          this.recordingStatusUpdateHandler = null
        }
        
        if (this.stepRecordedHandler) {
          window.removeEventListener('stepRecorded', this.stepRecordedHandler)
          this.stepRecordedHandler = null
        }
        
        if (this.recordingSessionRestoredHandler) {
          window.removeEventListener('recordingSessionRestored', this.recordingSessionRestoredHandler)
          this.recordingSessionRestoredHandler = null
        }
        
        if (this.recordingCleanedUpHandler) {
          window.removeEventListener('recordingCleanedUp', this.recordingCleanedUpHandler)
          this.recordingCleanedUpHandler = null
        }
      }
    }
  }
})